package com.firstsource.networking.ip.tracker.data.access;

import java.util.ArrayList;

import org.hibernate.Session;

import com.firstsource.networking.ip.tracker.data.HibernateUtil;
import com.firstsource.networking.ip.tracker.data.entities.Subnet;
import com.firstsource.networking.ip.tracker.util.IPManipulator;

public class SubnetDAO {

	private Session session = null ;

	public SubnetDAO() {
		session = HibernateUtil.currentSession() ;
	}

	public void saveOrUpdate(Subnet currSubnet) {
		session.beginTransaction() ;
		session.saveOrUpdate(currSubnet) ;
		session.getTransaction().commit() ;
	}

	public Subnet getSubnetByAddr(String network) {
		long net = IPManipulator.ip2Long(network) ;

		session.beginTransaction() ;
		Subnet retVal = (Subnet)session.createQuery("From Subnet where network=:network").setLong("network", net).list().get(0) ;
		session.getTransaction().commit() ;

		return retVal ;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Subnet> getSubnetsByName(String name) {
		session.beginTransaction() ;
		ArrayList<Subnet> retVal = (ArrayList)session.createQuery("From Subnet where name like :name").setString("name", name).list() ;
		session.getTransaction().commit() ;

		return retVal ;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Subnet> getSubnetsByRange(String start, String end) {
		long low, high ;
		low = IPManipulator.ip2Long(start) ;
		high = IPManipulator.ip2Long(end) ;
		session.beginTransaction() ;
		ArrayList<Subnet> retVal = (ArrayList)session.createQuery("From Subnet where network>=:start and network<=:end").setLong("start", low).setLong("end",high).list() ;
		session.getTransaction().commit() ;

		return retVal ;
	}
}
